package com.scqzy.shengchunqiang.sword2offer.day19;

import com.scqzy.shengchunqiang.structure.TreeNode;

import java.util.Objects;

/**
 * @Description: 剑指 Offer 68 - II. 二叉树的最近公共祖先
 * @Author 盛春强
 * @Date 2021/8/26 11:30
 */
public class LowestCommonAncestor2 {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (Objects.isNull(root) || root.val == p.val || root.val == q.val) {
            return root;
        }
        if (dfs(root.left, p) && dfs(root.left, q)) {
            return lowestCommonAncestor(root.left, p, q);
        } else if (dfs(root.right, p) && dfs(root.right, q)) {
            return lowestCommonAncestor(root.right, p, q);
        } else {
            return root;
        }
    }

    private boolean dfs(TreeNode root, TreeNode node) {
        if (Objects.isNull(root)) {
            return false;
        }
        if (root.val == node.val) {
            return true;
        }
        return dfs(root.left, node) || dfs(root.right, node);
    }
}
